import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

// ignore: must_be_immutable
class DebouncedMaterialButton extends StatefulWidget {
  final Widget _child;
  final VoidCallback _onPressed;
  final Duration _duration;
  final Color? _color;
  final Color? _textColor;

  DebouncedMaterialButton(
      {required Widget child,
      required VoidCallback onPressed,
      int debounceTimeMs = 200,
      Color? textColor,
      Color? color})
      : this._child = child,
        this._onPressed = onPressed,
        this._color = color,
        this._textColor = textColor,
        this._duration = Duration(milliseconds: debounceTimeMs);

  @override
  _DebouncedMaterialButtonState createState() =>
      _DebouncedMaterialButtonState();
}

class _DebouncedMaterialButtonState extends State<DebouncedMaterialButton> {
  late ValueNotifier<bool> _isEnabled;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _isEnabled = ValueNotifier<bool>(true);

    EasyLoading.addStatusCallback((status) {
      if (status == EasyLoadingStatus.dismiss) {
        _timer?.cancel();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: _isEnabled,
      builder: (context, isEnabled, child) => MaterialButton(
        color: widget._color,
        textColor: widget._textColor,
        onPressed: isEnabled as bool ? _onButtonPressed : null,
        child: widget._child,
      ),
    );
  }

  void _onButtonPressed() {
    EasyLoading.show(dismissOnTap: true);
    _isEnabled.value = false;
    widget._onPressed();
    _timer = Timer(widget._duration, () {
      _isEnabled.value = true;
      EasyLoading.dismiss();
    });
  }
}
